home *** CD-ROM | disk | FTP | other *** search
/ Ian & Stuart's Australian Mac 1993 September / September 93.iso / Archives / Fun, Tricks & Hacks / Windows / MSShell.c < prev    next >
C/C++ Source or Header  |  1992-06-14  |  29KB  |  801 lines

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Based on:
  4. #
  5. #    Apple Macintosh Developer Technical Support
  6. #
  7. #    MultiFinder-Aware Simple Sample Application
  8. #
  9. #        Beware of comments...
  10. #
  11. ------------------------------------------------------------------------------*/
  12.  
  13. /* Segmentation strategy:
  14.  
  15.    This program consists of three segments. Main contains most of the code,
  16.    including the MPW libraries, and the main program. Initialize contains
  17.    code that is only used once, during startup, and can be unloaded after the
  18.    program starts. %A5Init is automatically created by the Linker to initialize
  19.    globals for the MPW libraries and is unloaded right away. */
  20.  
  21.  
  22. /* SetPort strategy:
  23.  
  24.    Toolbox routines do not change the current port. In spite of this, in this
  25.    program we use a strategy of calling SetPort whenever we want to draw or
  26.    make calls which depend on the current port. This makes us less vulnerable
  27.    to bugs in other software which might alter the current port (such as the
  28.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  29.    Hopefully, this also makes the routines from this program more self-contained,
  30.    since they don't depend on the current port setting. */
  31.  
  32.  
  33. #include "MSWindows.h"
  34.  
  35.  
  36. /* The "g" prefix is used to emphasize that a variable is global. */
  37. MenuHandle        gMenus[menuCount];
  38.  
  39. /* gMac is used to hold the result of a SysEnvirons call. This makes
  40.    it convenient for any routine to check the environment. */
  41. SysEnvRec    gMac;                /* set up by Initialize */
  42.  
  43. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  44.    trap is available. If it is false, we know that we must call GetNextEvent. */
  45. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  46.  
  47. /* gInBackground is maintained by our osEvent handling routines. Any part of
  48.    the program can check it to find out if it is currently in the background. */
  49. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  50.  
  51. extern MSWindowPtr gPMWindow;
  52.  
  53. /*    Cursor regions */
  54. extern RgnHandle gFrameRgn;
  55. extern RgnHandle gUpRgn,gRightRgn,gURightRgn,gDRightRgn,gArrowRgn;
  56. extern RgnHandle gcUpRgn,gcRightRgn,gcURightRgn,gcDRightRgn,gcArrowRgn;
  57.  
  58.                                 /** MultiClick Checks **/
  59. EventRecord    gLastMouseDown;        /* Previous mouse down event        */
  60. EventRecord    gLastMouseUp;        /* Previous mouse up event            */
  61. short        gClicks;            /* Click counter, = 1 single click    */
  62.                                 /*                = 2 double click    */
  63.                                 /*    etc.                            */
  64.  
  65. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  66.    actual prototypes for parameter type checking. */
  67. void EventLoop( void );
  68. void DoEvent( EventRecord *event );
  69. void AdjustCursor( Point mouse, RgnHandle region );
  70. void GetGlobalMouse( Point *mouse );
  71. void DoUpdate( WindowPtr window );
  72. void DoActivate( WindowPtr window, Boolean becomingActive );
  73. void AdjustMenus( void );
  74. void Terminate( void );
  75. void Initialize( void );
  76. void ForceEnvirons( void );
  77. Boolean TrapAvailable( short tNumber, TrapType tType );
  78. void AlertUser( void );
  79.  
  80.  
  81. extern void _DataInit();
  82.  
  83. /* This routine is part of the MPW runtime library. This external
  84.    reference to it is done so that we can unload its segment, %A5Init. */
  85.  
  86.  
  87. #pragma segment Main
  88. void main(void)
  89. {
  90.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  91.     
  92.     /* 1.01 - call to ForceEnvirons removed */
  93.     
  94.     /*    If you have stack requirements that differ from the default,
  95.         then you could use SetApplLimit to increase StackSpace at 
  96.         this point, before calling MaxApplZone. */
  97.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  98.  
  99.     Initialize();                    /* initialize the program */
  100.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  101.  
  102.     EventLoop();                    /* call the main event loop */
  103. }
  104.  
  105.  
  106. /*    Get events forever, and handle them by calling DoEvent.
  107.     Get the events by calling WaitNextEvent, if it's available, otherwise
  108.     by calling GetNextEvent. Also call AdjustCursor each time through the loop. */
  109.  
  110. void EventLoop(void)
  111. {
  112.     RgnHandle    cursorRgn;
  113.     Boolean        gotEvent;
  114.     EventRecord    event;
  115.     Point        mouse;
  116.  
  117.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  118.     do {
  119.         /* use WNE if it is available */
  120.         if ( gHasWaitNextEvent ) {
  121.             GetGlobalMouse(&mouse);
  122.             AdjustCursor(mouse, cursorRgn);
  123.             gotEvent = WaitNextEvent(everyEvent, &event, -1, cursorRgn);
  124.         }
  125.         else {
  126.             SystemTask();
  127.             gotEvent = GetNextEvent(everyEvent, &event);
  128.         }
  129.  
  130.         GameTime();
  131.  
  132.         if ( gotEvent ) {
  133.             /* make sure we have the right cursor before handling the event */
  134.             AdjustCursor(event.where, cursorRgn);
  135.             DoEvent(&event);
  136.         }
  137.         /*    If you are using modeless dialogs that have editText items,
  138.             you will want to call IsDialogEvent to give the caret a chance
  139.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  140.             for a non-NIL value before calling IsDialogEvent. */
  141.     } while ( true );    /* loop forever; we quit via ExitToShell */
  142. } /*EventLoop*/
  143.  
  144. MSChildPtr GetFirstChild(MSWindowPtr window)
  145. {
  146.     MSChildPtr    MSChild = nil;
  147.     
  148.     if ( IsAppWindow((WindowPtr) window) && (MSChild = window->child))
  149.         while ((MSChild->origin.h & kOffscreenOffset) && (MSChild->next != nil)) 
  150.             MSChild = MSChild->next;
  151.     return(MSChild);
  152. }
  153.  
  154. /*    set the active flag for front child and parent (i.e. the base child) */
  155. void SetActive(WindowPtr window,Boolean becomingActive)
  156. {
  157.     MSChildPtr    MSChild;
  158.     
  159.     MSChild = GetFirstChild((MSWindowPtr)window);
  160.     MSChild->active = becomingActive;        // front child for active draw
  161.     while (MSChild->next != nil) 
  162.         MSChild = MSChild->next;
  163.     MSChild->active = becomingActive;        // parent for active draw
  164. }
  165.  
  166. void BringChildFront(WindowPtr window,Point where,Boolean doUpdate)
  167. {
  168.     Point    pt;
  169.     Rect    r;
  170.     MSChildPtr    MSChild,MSFront,*pParent;
  171.  
  172.     pParent = &((MSWindowPtr)window)->child;
  173.     MSFront = *pParent;
  174.     MSChild = MSFront;
  175.     if (doUpdate && (MSChild->next != nil)) {
  176.         SetOrigin(0,0);
  177.         r = MSChild->portRect;
  178.         OffsetRect(&r,MSChild->origin.h,MSChild->origin.v);
  179.         EraseRect(&r);
  180.     }
  181.     while (MSChild->next != nil) {        // don't swap parent => base child
  182.         MSChild->active = false;        // front child may become inactive
  183.         SetOrigin( -MSChild->origin.h, -MSChild->origin.v);
  184.         pt = where;
  185.         GlobalToLocal(&pt);
  186.         if (PtInRect(pt,&MSChild->portRect)) {
  187.             if (MSChild != MSFront) {                    // if not already in front
  188.                 *pParent = MSChild->next;                // link child's next to parent's next
  189.                 MSChild->next = MSFront;                // link front to after child
  190.                 ((MSWindowPtr)window)->child = MSChild;    // link child to front
  191.             }
  192.             doUpdate = true;
  193.             break;        // skip out
  194.         }
  195.         pParent = &MSChild->next;
  196.         MSChild = *pParent;
  197.     }
  198.     SetOrigin(0,0);
  199.     SetActive(window,true);
  200.     if (doUpdate) {
  201.         InvalRect(&window->portRect);
  202.         if (MSChild->next != nil) {
  203.             r = MSChild->portRect;
  204.             OffsetRect(&r,MSChild->origin.h,MSChild->origin.v);
  205.             EraseRect(&r);
  206.         }
  207.         BeginUpdate(window);
  208.         DrawWindow(window);
  209.         EndUpdate(window);
  210.     }
  211.     SetCursorRgns();
  212. }
  213.  
  214. /* Do the right thing for an event. Determine what kind of event it is, and call
  215.  the appropriate routines. */
  216.  
  217. void DoEvent(EventRecord *event)
  218. {
  219.     short        part, err;
  220.     long        result;
  221.     WindowPtr    window;
  222.     Boolean        hit;
  223.     char        key;
  224.     Point        aPoint;
  225.     Rect        dragRect;
  226.     
  227.     switch ( event->what ) {
  228.         case mouseDown:
  229.             part = FindWindow(event->where, &window);
  230.             if (window)
  231.                 SetPort(window);    // added ??
  232.             switch ( part ) {
  233.                 case inMenuBar:                /* process a mouse menu command (if any) */
  234.                     AdjustMenus();
  235.                     result = MenuSelect(event->where);
  236.                     DoMenuCommand(GetFirstChild((MSWindowPtr)window),gMenus[HiWrd(result)],result);
  237.                     break;
  238.                 case inSysWindow:            /* let the system handle the mouseDown */
  239.                     SystemClick(event, window);
  240.                     break;
  241.                 case inContent:
  242.                     if ( window != FrontWindow() ) {    // allow "do first click"
  243.                         SelectWindow(window);
  244.                         if ( IsAppWindow(window) ) {    // update it now
  245.                             SetPort(window);
  246.                             BringChildFront(window,event->where,true);
  247.                         }
  248.                         DoEvent(event);
  249.                     } else
  250.                         if (!ContentClick(event, window))
  251.                             if (!DragChild(window, event->where))
  252.                                 goto doDrag;
  253.                     break;
  254.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  255.             doDrag:    SetRect(&dragRect,4,24,qd.screenBits.bounds.right - 4, 
  256.                                         qd.screenBits.bounds.bottom - 4);
  257.                     DragWindow(window, event->where, &dragRect);
  258.                     SetCursorRgns();
  259.                     break;
  260.                 case inGrow:
  261.                     break;
  262.                 case inZoomIn:
  263.                 case inZoomOut:
  264.                     hit = TrackBox(window, event->where, part);
  265.                     if ( hit ) {
  266.                         SetPort(window);                /* the window must be the current port... */
  267.                         EraseRect(&window->portRect);    /* because of a bug in ZoomWindow */
  268.                         ZoomWindow(window, part, true);    /* note that we invalidate and erase... */
  269.                         InvalRect(&window->portRect);    /* to make things look better on-screen */
  270.                         SetCursorRgns();
  271.                     }
  272.                     break;
  273.             }
  274.             gLastMouseDown = *event;    /* Save for multi-click checking */
  275.             break;
  276.         case mouseUp:                    /* Mouse was released                */
  277.             gLastMouseUp = *event;        /* Save for multi-click checking */
  278.             break;
  279.         case keyDown:
  280.         case autoKey:                        /* check for menukey equivalents */
  281.             key = event->message & charCodeMask;
  282.             if ( event->modifiers & cmdKey )            /* Command key down */
  283.                 if ( event->what == keyDown ) {
  284.                     AdjustMenus();                        /* enable/disable/check menu items properly */
  285.                     result = MenuKey(key);
  286.                     DoMenuCommand(GetFirstChild((MSWindowPtr)window),gMenus[HiWrd(result)],result);
  287.                 }
  288.             break;
  289.         case activateEvt:
  290.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  291.             break;
  292.         case updateEvt:
  293.             DoUpdate((WindowPtr) event->message);
  294.             break;
  295.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  296.             to a diskEvt, so that the user can format a floppy. */
  297.         case diskEvt:
  298.             if ( HiWrd(event->message) != noErr ) {
  299.                 SetPt(&aPoint, kDILeft, kDITop);
  300.                 err = DIBadMount(aPoint, event->message);
  301.             }
  302.             break;
  303.         case kOSEvent:
  304.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  305.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  306.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  307.                     gInBackground = (event->message & kResumeMask) == 0;
  308.                     DoActivate(FrontWindow(), !gInBackground);
  309.                     break;
  310.             }
  311.             break;
  312.     }
  313. } /*DoEvent*/
  314.  
  315. /*    Check if mouse down event is part of a multiple click    */
  316.  
  317. void CountClicks(EventRecord *macEvent)
  318. {                                        /* To be a multiclick, clicks must:    */
  319. short    h,v;                            /*   • Hit the same view            */
  320.                                         /*   • Occur within a certain time    */
  321.                                         /*   • Be "close" in space            */
  322.     h = gLastMouseDown.where.h - macEvent->where.h;
  323.     if (h < 0) h -= h;
  324.     v = gLastMouseDown.where.v - macEvent->where.v;
  325.     if (v < 0) v -= v;
  326.     if ( ((macEvent->when - gLastMouseUp.when) < GetDblTime())  &&
  327.          ((h + v) < 10) ) {
  328.         gClicks++;
  329.     } else {                            /* Reset click counter */
  330.         gClicks = 1;
  331.     }
  332. }
  333.  
  334. void GetFrameRgns(Rect *portRect)
  335. {
  336.     Rect rect;
  337.     
  338.     rect = *portRect;
  339.     RectRgn(gFrameRgn,&rect);
  340.     InsetRect(&rect,kGrowBorder+1,kGrowBorder+1);
  341.     RectRgn(gArrowRgn,&rect);
  342.     DiffRgn(gFrameRgn,gArrowRgn,gFrameRgn);                // the whole frame
  343.  
  344.     CopyRgn(gFrameRgn,gURightRgn);
  345.     OffsetRgn(gArrowRgn,kPictWidth,kPictWidth);            // down to right
  346.     DiffRgn(gURightRgn,gArrowRgn,gURightRgn);
  347.     OffsetRgn(gArrowRgn,-2*kPictWidth,-2*kPictWidth);    // up to left
  348.     DiffRgn(gURightRgn,gArrowRgn,gURightRgn);
  349.  
  350.     CopyRgn(gFrameRgn,gDRightRgn);
  351.     OffsetRgn(gArrowRgn,2*kPictWidth,0);                // up to right
  352.     DiffRgn(gDRightRgn,gArrowRgn,gDRightRgn);
  353.     OffsetRgn(gArrowRgn,-2*kPictWidth,2*kPictWidth);    // down to left
  354.     DiffRgn(gDRightRgn,gArrowRgn,gDRightRgn);
  355.  
  356.     OffsetRgn(gArrowRgn,kPictWidth,-kPictWidth);        // back to center
  357.     
  358.     rect = *portRect;
  359.     InsetRect(&rect,kPictWidth,0);
  360.     RectRgn(gUpRgn,&rect);
  361.     SectRgn(gFrameRgn,gUpRgn,gUpRgn);
  362.  
  363.     rect = *portRect;
  364.     InsetRect(&rect,0,kPictWidth);
  365.     RectRgn(gRightRgn,&rect);
  366.     SectRgn(gFrameRgn,gRightRgn,gRightRgn);
  367. }
  368.  
  369. /*    Change the cursor's shape, depending on its position. This also calculates the region
  370.     where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  371.     that region, an event would be generated, causing this routine to be called,
  372.     allowing us to change the region to the region the mouse is currently in. If
  373.     there is more to the event than just “the mouse moved”, we get called before the
  374.     event is processed to make sure the cursor is the right one. In any (ahem) event,
  375.     this is called again before we     fall back into WNE. */
  376.  
  377. void SetCursorRgns()
  378. {
  379.     WindowPtr        window;
  380.     PixMapHandle    portPixMap;
  381.     Rect            rect;
  382.     MSChildPtr        MSChild;
  383.  
  384.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  385.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  386.         /* calculate regions for different cursor shapes */
  387.  
  388.         /* start with a big, big rectangular region */
  389.         SetRectRgn(gArrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  390.  
  391.         /* calculate Rgns */
  392.         if ( IsAppWindow(window) ) {
  393.             SetPort(window);    /* make a global version of the viewRect */
  394.             portPixMap = ((CGrafPtr)window)->portPixMap;
  395.  
  396.             SetOrigin(-(*portPixMap)->bounds.left,-(*portPixMap)->bounds.top);
  397.             GetFrameRgns(&window->portRect);            // main cursor regions
  398.  
  399.             if (window == gPMWindow) {
  400.                 MSChild = GetFirstChild((MSWindowPtr)window);
  401.                 if (MSChild->next != nil) {
  402.                     CopyRgn(gUpRgn,gcUpRgn);            // save cursor regions
  403.                     CopyRgn(gRightRgn,gcRightRgn);
  404.                     CopyRgn(gURightRgn,gcURightRgn);
  405.                     CopyRgn(gDRightRgn,gcDRightRgn);
  406.                     CopyRgn(gArrowRgn,gcArrowRgn);
  407.                     
  408.                     rect = MSChild->portRect;
  409. //                    OffsetRect(&rect,(*portPixMap)->bounds.left + MSChild->origin.h,
  410. //                            (*portPixMap)->bounds.top + MSChild->origin.v);
  411.                     OffsetRect(&rect,MSChild->origin.h,MSChild->origin.v);
  412.                     GetFrameRgns(&rect);                // get child cursor regions
  413.     
  414.                     UnionRgn(gcUpRgn,gUpRgn,gUpRgn);    // combine cursor regions
  415.                     UnionRgn(gcRightRgn,gRightRgn,gRightRgn);
  416.                     UnionRgn(gcURightRgn,gURightRgn,gURightRgn);
  417.                     UnionRgn(gcDRightRgn,gDRightRgn,gDRightRgn);
  418.                     DiffRgn(gcArrowRgn,gFrameRgn,gArrowRgn);
  419.                 }
  420.             }
  421.             SetOrigin(0,0);
  422.         }
  423.     }
  424. }
  425.  
  426. void AdjustCursor(Point mouse,RgnHandle region)
  427. {
  428.     WindowPtr    window;
  429.  
  430.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  431.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  432.         /* change the cursor and the region parameter */
  433.         if ( PtInRgn(mouse,gArrowRgn) ) {
  434.             SetCursor(*GetCursor(kArrowCursor));
  435.             CopyRgn(gArrowRgn,region);
  436.         } else
  437.         if ( PtInRgn(mouse,gURightRgn) ) {
  438.             SetCursor(*GetCursor(kURightCursor));
  439.             CopyRgn(gURightRgn,region);
  440.         } else
  441.         if ( PtInRgn(mouse,gDRightRgn) ) {
  442.             SetCursor(*GetCursor(kDRightCursor));
  443.             CopyRgn(gDRightRgn,region);
  444.         } else
  445.         if ( PtInRgn(mouse,gRightRgn) ) {
  446.             SetCursor(*GetCursor(kHoriCursor));
  447.             CopyRgn(gRightRgn,region);
  448.         } else
  449.         if ( PtInRgn(mouse,gUpRgn) ) {
  450.             SetCursor(*GetCursor(kVertCursor));
  451.             CopyRgn(gUpRgn,region);
  452.         } else {
  453.             InitCursor();
  454.             CopyRgn(gArrowRgn,region);
  455.         }
  456.     }
  457. } /* AdjustCursor */
  458.  
  459.  
  460. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  461.     it will return either a pending event or a null event. In either case,
  462.     the where field of the event record will contain the current position
  463.     of the mouse in global coordinates and the modifiers field will reflect
  464.     the current state of the modifiers. Another way to get the global
  465.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  466.     being sure that thePort is set to a valid port. */
  467.  
  468. void GetGlobalMouse(Point *mouse)
  469. {
  470.     EventRecord    event;
  471.     
  472.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  473.     *mouse = event.where;                /* just the mouse position */
  474. } /*GetGlobalMouse*/
  475.  
  476.  
  477. /*    This is called when an update event is received for a window.
  478.     It calls DrawWindow to draw the contents of an application window.
  479.     As an effeciency measure that does not have to be followed, it
  480.     calls the drawing routine only if the visRgn is non-empty. This
  481.     will handle situations where calculations for drawing or drawing
  482.     itself is very time-consuming. */
  483.  
  484. void DoUpdate(WindowPtr window)
  485. {
  486.     if ( IsAppWindow(window) ) {
  487.         SetPort(window);
  488.         BeginUpdate(window);                /* this sets up the visRgn */
  489.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  490.             DrawWindow(window);
  491.         EndUpdate(window);
  492.     }
  493. } /*DoUpdate*/
  494.  
  495.  
  496. /*    This is called when a window is activated or deactivated.
  497.     In Sample, the Window Manager's handling of activate and
  498.     deactivate events is sufficient. Other applications may have
  499.     TextEdit records, controls, lists, etc., to activate/deactivate. */
  500.  
  501. void DoActivate(WindowPtr window,Boolean becomingActive)
  502. {
  503.     if ( IsAppWindow(window) ) {
  504.         SetActive(window,becomingActive);
  505.         SetPort(window);
  506.         InvalRect(&window->portRect);    // get the selection & bounds updated
  507.     }
  508. } /*DoActivate*/
  509.  
  510.  
  511. /*    Enable and disable menus based on the current state.
  512.     The user can only select enabled menu items. We set up all the menu items
  513.     before calling MenuSelect or MenuKey, since these are the only times that
  514.     a menu item can be selected. Note that MenuSelect is also the only time
  515.     the user will see menu items. This approach to deciding what enable/
  516.     disable state a menu item has the advantage of concentrating all
  517.     the decision-making in one routine, as opposed to being spread throughout
  518.     the application. Other application designs may take a different approach
  519.     that is just as valid. */
  520.  
  521. void AdjustMenus(void)
  522. {
  523.     WindowPtr    window;
  524.     MenuHandle    menu;
  525.  
  526.     window = FrontWindow();
  527.  
  528.     menu = gMenus[mEditInx];
  529.     if ( IsDAWindow(window) ) {        /* a desk accessory might need the edit menu… */
  530.         EnableItem(menu, iUndo);
  531.         EnableItem(menu, iCut);
  532.         EnableItem(menu, iCopy);
  533.         EnableItem(menu, iClear);
  534.         EnableItem(menu, iPaste);
  535.     } else {                        /* …but we don’t use it */
  536.         DisableItem(menu, iUndo);
  537.         DisableItem(menu, iCut);
  538.         DisableItem(menu, iCopy);
  539.         DisableItem(menu, iClear);
  540.         DisableItem(menu, iPaste);
  541.     }
  542. } /*AdjustMenus*/
  543.  
  544.  
  545. /* Close a window. This handles desk accessory and application windows. */
  546.  
  547. /*    1.01 - At this point, if there was a document associated with a
  548.     window, you could do any document saving processing if it is 'dirty'.
  549.     DoCloseWindow would return true if the window actually closed, i.e.,
  550.     the user didn’t cancel from a save dialog. This result is handy when
  551.     the user quits an application, but then cancels the save of a document
  552.     associated with a window. */
  553.  
  554. Boolean DoCloseWindow(WindowPtr window)
  555. {
  556.     if ( IsDAWindow(window) )
  557.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  558.     else if ( IsAppWindow(window) )
  559.         CloseWindow(window);
  560.     return true;
  561. } /*DoCloseWindow*/
  562.  
  563.  
  564. /**************************************************************************************
  565. *** 1.01 DoCloseBehind(window) was removed ***
  566.  
  567.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  568.     and not having to worry about updating the windows, but it suffered
  569.     from a fatal flaw. If a desk accessory owned two windows, it would
  570.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  571.     got around to calling DoCloseWindow for that other window that was already
  572.     closed, things would go very poorly. Another option would be to have a
  573.     procedure, GetRearWindow, that would go through the window list and return
  574.     the last window. Instead, we decided to present the standard approach
  575.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  576.     has a potential benefit in that the window whose document needs to be saved
  577.     may be visible since it is the front window, therefore decreasing the
  578.     chance of user confusion. For aesthetic reasons, the windows in the
  579.     application should be checked for updates periodically and have the
  580.     updates serviced.
  581. **************************************************************************************/
  582.  
  583.  
  584. /* Clean up the application and exit. We close all of the windows so that
  585.  they can update their documents, if any. */
  586.  
  587. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  588.     shell, but will return instead. */
  589.  
  590. void Terminate(void)
  591. {
  592.     WindowPtr    aWindow;
  593.     Boolean        closed;
  594.     
  595.     closed = true;
  596.     do {
  597.         aWindow = FrontWindow();                /* get the current front window */
  598.         if (aWindow != nil)
  599.             closed = DoCloseWindow(aWindow);    /* close this window */    
  600.     }
  601.     while (closed && (aWindow != nil));
  602.     if (closed)
  603.         ExitToShell();                            /* exit if no cancellation */
  604. } /*Terminate*/
  605.  
  606.  
  607. /*    Set up the whole world, including global variables, Toolbox managers,
  608.     and menus. We also create our one application window at this time.
  609.     Since window storage is non-relocateable, how and when to allocate space
  610.     for windows is very important so that heap fragmentation does not occur.
  611.     Because Sample has only one window and it is only disposed when the application
  612.     quits, we will allocate its space here, before anything that might be a locked
  613.     relocatable object gets into the heap. This way, we can force the storage to be
  614.     in the lowest memory available in the heap. Window storage can differ widely
  615.     amongst applications depending on how many windows are created and disposed. */
  616.  
  617. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  618.     this module. If an error is detected, instead of merely doing an ExitToShell,
  619.     which leaves the user without much to go on, we call AlertUser, which puts
  620.     up a simple alert that just says an error occurred and then calls ExitToShell.
  621.     Since there is no other cleanup needed at this point if an error is detected,
  622.     this form of error- handling is acceptable. If more sophisticated error recovery
  623.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  624.  
  625. #pragma segment Initialize
  626. void Initialize(void)
  627. {
  628.     long        total, contig;
  629.     EventRecord event;
  630.     short        count;
  631.  
  632.     gInBackground = false;
  633.  
  634.     InitGraf((Ptr) &qd.thePort);
  635.     InitFonts();
  636.     InitWindows();
  637.     InitMenus();
  638.     TEInit();
  639.     InitDialogs(nil);
  640.     InitCursor();
  641.     
  642.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  643.          if you are using it. */
  644.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  645.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  646.         of checking for port availability themselves. */
  647.     
  648.     /*    This next bit of code is necessary to allow the default button of our
  649.         alert be outlined.
  650.         1.02 - Changed to call EventAvail so that we don't lose some important
  651.         events. */
  652.      
  653.     for (count = 1; count <= 3; count++)
  654.         EventAvail(everyEvent, &event);
  655.     
  656.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  657.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  658.         call to SysEnvirons by calling it after initializing AppleTalk. */
  659.      
  660.     SysEnvirons(kSysEnvironsVersion, &gMac);
  661.     
  662.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  663.     
  664.     if (gMac.machineType < 0) AlertUser();
  665.     
  666.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  667.         in TrapAvailable if a tool trap value is out of range. */
  668.         
  669.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  670.  
  671.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  672.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  673.         MultiFinder we needed. This did not work well because it assumed too much about
  674.         the relationship between what we asked MultiFinder for and what we would actually
  675.         get back, as well as how to measure it. Instead, we will use an alternate
  676.         method comprised of two steps. */
  677.      
  678.     /*    It is better to first check the size of the application heap against a value
  679.         that you have determined is the smallest heap the application can reasonably
  680.         work in. This number should be derived by examining the size of the heap that
  681.         is actually provided by MultiFinder when the minimum size requested is used.
  682.         The derivation of the minimum size requested from MultiFinder is described
  683.         in Sample.h. The check should be made because the preferred size can end up
  684.         being set smaller than the minimum size by the user. This extra check acts to
  685.         insure that your application is starting from a solid memory foundation. */
  686.      
  687.     if ((long) GetApplLimit() - (long) ApplicZone() < kMinHeap) AlertUser();
  688.     
  689.     /*    Next, make sure that enough memory is free for your application to run. It
  690.         is possible for a situation to arise where the heap may have been of required
  691.         size, but a large scrap was loaded which left too little memory. To check for
  692.         this, call PurgeSpace and compare the result with a value that you have determined
  693.         is the minimum amount of free memory your application needs at initialization.
  694.         This number can be derived several different ways. One way that is fairly
  695.         straightforward is to run the application in the minimum size configuration
  696.         as described previously. Call PurgeSpace at initialization and examine the value
  697.         returned. However, you should make sure that this result is not being modified
  698.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  699.         PurgeSpace. Make sure to remove that call before shipping, though. */
  700.     
  701.     /* ZeroScrap(); */
  702.  
  703.     PurgeSpace(&total, &contig);
  704.     if (total < kMinSpace) AlertUser();
  705.     
  706.     for (count = kMaxMasters; count > 0; count--)
  707.         MoreMasters();        // get some spare handles
  708.  
  709.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  710.         to check memory is that we can now give the user an alert to tell him/her what
  711.         happened. Although it is possible that the memory situation could be worsened by
  712.         displaying an alert, MultiFinder would gracefully exit the application with
  713.         an informative alert if memory became critical. Here we are acting more
  714.         in a preventative manner to avoid future disaster from low-memory problems. */
  715.     
  716.     if ( !InitializeApp() )
  717.         AlertUser();
  718.         
  719.     /*
  720.     **    Set up menus last, since the menu drawing can then use 
  721.     **    any palette we have for our window. 
  722.     **    Makes the Apple look better, in particular.
  723.     */
  724.     SetUpMenus();
  725.  
  726. } /*Initialize*/
  727.  
  728. /*    Check to see if a given trap is implemented. This is only used by the
  729.     Initialize routine in this program, so we put it in the Initialize segment.
  730.     The recommended approach to see if a trap is implemented is to see if
  731.     the address of the trap routine is the same as the address of the
  732.     Unimplemented trap. */
  733. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  734.     if a ToolTrap is out of range of a pre-MacII ROM. */
  735.  
  736. #pragma segment Initialize
  737. Boolean TrapAvailable(short tNumber,TrapType tType)
  738. {
  739.     if ( ( tType == ToolTrap ) &&
  740.         ( gMac.machineType > envMachUnknown ) &&
  741.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  742.         tNumber = tNumber & 0x03FF;
  743.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  744.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  745.     }
  746.     return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
  747. } /*TrapAvailable*/
  748.  
  749.  
  750. #pragma segment Main
  751.  
  752. /*    Check to see if a window belongs to the application. If the window pointer
  753.     passed was NIL, then it could not be an application window. WindowKinds
  754.     that are negative belong to the system and windowKinds less than userKind
  755.     are reserved by Apple except for windowKinds equal to dialogKind, which
  756.     mean it is a dialog.
  757.     1.02 - In order to reduce the chance of accidentally treating some window
  758.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  759.     is userKind. If you add different kinds of windows to Sample you'll need
  760.     to change how this all works. */
  761.  
  762. Boolean IsAppWindow(WindowPtr window)
  763. {
  764.     extern WindowPtr    gMineWindow,gAlertWindow;
  765.     short        windowKind;
  766.  
  767.     if ( window == nil )
  768.         return false;
  769.     else {    /* application windows have windowKinds = userKind (8) */
  770.         windowKind = ((WindowPeek) window)->windowKind;
  771.         return (window == gPMWindow || window == gMineWindow || window == gAlertWindow );
  772.     }
  773. } /*IsAppWindow*/
  774.  
  775.  
  776. /* Check to see if a window belongs to a desk accessory. */
  777.  
  778. Boolean IsDAWindow(WindowPtr window)
  779. {
  780.     if ( window == nil )
  781.         return false;
  782.     else    /* DA windows have negative windowKinds */
  783.         return ((WindowPeek) window)->windowKind < 0;
  784. } /*IsDAWindow*/
  785.  
  786.  
  787. /*    Display an alert that tells the user an error occurred, then exit the program.
  788.     This routine is used as an ultimate bail-out for serious errors that prohibit
  789.     the continuation of the application. Errors that do not require the termination
  790.     of the application should be handled in a different manner. Error checking and
  791.     reporting has a place even in the simplest application. The error number is used
  792.     to index an 'STR#' resource so that a relevant message can be displayed. */
  793.  
  794. void AlertUser(void)
  795. {
  796.     short        itemHit;
  797.  
  798.     SetCursor(*GetCursor(132));    //    kArrowCursor
  799.     itemHit = Alert(rUserAlert, nil);
  800.     ExitToShell();
  801. } /* AlertUser */